<?php

// +----------------------------------------------------------------------

// | OneThink [ WE CAN DO IT JUST THINK IT ]

// +----------------------------------------------------------------------

// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.

// +----------------------------------------------------------------------

// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>

// +----------------------------------------------------------------------



namespace Home\Model;

use Think\Model;



/**
 * 文档基础模型
 */

class MessageModel extends Model{



	/* 自动验证规则 */

	protected $_validate = array(

		// array('name', '/^[a-zA-Z]\w{0,30}$/', '文档标识不合法', self::VALUE_VALIDATE, 'regex', self::MODEL_BOTH),

		// array('name', '', '标识已经存在', self::VALUE_VALIDATE, 'unique', self::MODEL_BOTH),

		array('title', 'require', '标题不能为空', self::VALUE_VALIDATE, 'regex', self::MODEL_BOTH),

		array('dianhua', 'require', '电话不能为空', self::MUST_VALIDATE , 'regex', self::MODEL_INSERT),

		array('xiangqing', 'require', '详情不能为空', self::EXISTS_VALIDATE , 'regex', self::MODEL_UPDATE),

		// array('category_id,type', 'checkCategory', '内容类型不正确', self::MUST_VALIDATE , 'callback', self::MODEL_INSERT),

		// array('category_id', 'checkCategory', '该分类不允许发布内容', self::EXISTS_VALIDATE , 'callback', self::MODEL_BOTH),

		// array('model_id,category_id', 'checkModel', '该分类没有绑定当前模型', self::MUST_VALIDATE , 'callback', self::MODEL_INSERT),

	);



	/* 自动完成规则 */

	protected $_auto = array(

		array('create_time', NOW_TIME, self::MODEL_INSERT),

	);
	/**
	 * 添加提示
	 * $sid 发送人ID
	 * $rid 接收人ID
	 * $content 发送内容
	 * $type   信息类型，1自荐，2课程被预定，3预定成功，4其他系统信息
	 * $time   发送时间
	 * 
	 */
	public function addMessages($sid,$rid,$content,$type,$time){
		$data['sid'] 	 = $sid;
		$data['rid'] 	 = $rid;
		$data['content'] = $content;
		$data['type']    = $type;
		$data['time']    = $time;
		$this ->add($data);
	}
	/**

	 * [selectAll description]

	 * @param  [type]  $uid [description]  查找消息的方法

	 * @return [type]       [description]

	 */

	public function selectAll($uid,$Page){

		$where['m.rid']    = $uid;

		$where['m.status'] = 1;

		$data = $this

				 ->alias('m')

				 //->field('m.id,m.sid,m.rid,m.content,m.type,m.status,m.time,u.nickname,u.sex,u.age,u.logo,u.id as uid')
				 
				 ->field('m.id,m.sid,m.rid,m.content,m.type,m.status,m.time')

				 //->join('tutor_user_member as u on m.sid = u.id')
				 ->join('tutor_user_member as u on m.rid = u.id')//lkl修改sql错误

				 ->where($where)

				 ->order('m.time desc')

				 ->limit($Page->firstRow.','.$Page->listRows)

				 ->select();

		// foreach ($data as $key => &$value) {

		// 	if($value['type'] == 2){

		// 		$value['content'] = "您收到了".$value['nickname']."关于钢琴课的预订，具体课程内容请在我的课程中查看，请尽快联系您的学生，以免ta等待太久退订哦！";

		// 	}else if($value['type'] == 3){

		// 		$value['content'] = "您收到了".$value['nickname']."关于钢琴课的咨询！<br />".$value['content'];

		// 	}else if($value['type'] == 4){

		// 		$value['content'] = "您收到了管理员通知:<br />".$value['content'];

		// 	}

		// }
/* lkl修改自荐人信息 S*/
		foreach($data as $key=>$val){
			if($val['sid'] > 0){
				$user = D('UserMember')->showUser($val['sid']);
				$data[$key]['nickname'] = $user['nickname'];
				$data[$key]['sex'] = $user['sex'];
				$data[$key]['age'] = $user['age'];
				$data[$key]['logo'] = $user['logo'];
				$data[$key]['uid'] = $user['id'];
			}
		}
		/* lkl修改自荐人信息 E*/
		return $data;

	}

	/**

	 * [showNum description]查找现在未读的消息个数

	 * @param  [type] $id [description]

	 * @return [type]     [description]

	 */

	public function showNum($id){

		$map['rid'] 	= $id;

		$map['remind']  = 1;

		return $this ->where($map)->count();

	}

	/**

	 *把消息提示状态改变

	 */

	public function delMsg($id){

		$map['rid'] = $id;

		$this ->where($map) ->save(array('remind' => 2));

	}

	public function ajaxDel($ids){

		return $this ->where(array('id' =>array('in',$ids))) ->save(array('status' => 2));

	}

	/**

	 * 给所有人发消息

	 * $uid   代表自己

	 * $cid   代表教师

	 * $teach 教师收到的钱

	 * $econ  平台收到的钱

	 * $salary 总的钱数

	 */

	public function MsgAll($uid,$cid,$teach){

		$m=D('Message');

		$m->startTrans();//开启事物

		$data   = $m ->add($arr);

		$brr = array(

			'sid'      => 0,

			'rid'      => $cid,

			'content'  => "你的授课已完成,收入".$teach."元",

			'type'     => 4,

			'time'     => time()

			);

		$data1  = $m ->add($brr);

		if($arr && $brr){

			$m->commit();//成功则提交

			D('Account') ->addAccounts($uid,$cid,$teach);

			return true;

		}else{

			$m->rollback();//不成功，则回滚

			return false;

		}

	}

	/**

	 * 自定义分页

	 * @return [type] [description]

	 */

	public function showPage($uid){

		$where['rid']    = $uid;

		$where['status'] = 1;

		$count = $this->where($where)->count();// 查询满足要求的总记录数

		$Page  = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)

		return $Page;

	}

	/**

	 *退订的时候发消息

	 */

	public function tuiding($id,$cid){

		$this ->startTrans();//开启事物

		  $arr = array(

		  	'sid'     => 0,

		  	'rid'      => $id,

		  	'content' => "您提交的退订已通过，未上部分的课程款将打回给您，请注意查收，谢谢您的支持！",

		  	'type'    => 4,

		  	'time'    => time()

		  	);

		  $data = D('Home/Course') -> field('uid') ->where(array('id' =>$cid)) ->find();

		  $name = D('Home/UserMember') ->field('nickname') ->where(array('id' =>$id)) ->find();

		  $brr  = array(

		  	'sid'     => 0,

		  	'rid'      => $data['uid'],

		  	'content' => "您的学生".$name['nickname']."已退订通过，平台将会把您已授课部分的课程款将打给您，谢谢您的支持。",

		  	'type'    => 4,

		  	'time'    => time()

		  	);

		  $data1 = $this ->add($arr);

		  $data2 = $this ->add($brr);

		if($data1 && $data2){

			$this->commit();//成功则提交

			return true;

		}else{

			$this->rollback();//不成功，则回滚

			return false;

		}

	}



	/*

	 *短信的接口

	 */

	public function sendSms($mobile,$content){

		$flag = 0;

		$params='';//要post的数据

		$verify = rand(123456, 999999);//获取随机验证码

		//以下信息自己填以下

		$argv = array(

			'name'=>'13811286300',     //必填参数。用户账号

			'pwd'=>'DC062075695DF35084F0FDC4374A',     //必填参数。（web平台：基本资料中的接口密码）

			'content'=>$content,   //必填参数。发送内容（1-500 个汉字）UTF-8编码

			'mobile'=>$mobile,   //必填参数。手机号码。多个以英文逗号隔开

			'stime'=>'',   //可选参数。发送时间，填写时已填写的时间发送，不填时为当前时间发送

			'sign'=>'全民教学公众平台',    //必填参数。用户签名。

			'type'=>'pt',  //必填参数。固定值 pt

			'extno'=>''    //可选参数，扩展码，用户定义扩展码，只能为数字

		);

		//print_r($argv);exit;

		//构造要post的字符串

		//echo $argv['content'];

		foreach ($argv as $key=>$value) {

			if ($flag!=0) {

				$params .= "&";

				$flag = 1;

			}

			$params.= $key."="; $params.= urlencode($value);// urlencode($value);

			$flag = 1;

		}

			$url = "http://web.duanxinwang.cc/asmx/smsservice.aspx?".$params; //提交的url地址

			$con= substr( file_get_contents($url), 0, 1 );  //获取信息发送后的状态

			session('verify',$verify);

			if($con == '0'){

				D('Home/Sms') ->addSms($argv,1);

				return ("发送成功!");

			}else{

				D('Home/Sms') ->addSms($argv,2);

				return ("发送失败!'");

			}

	}

	/**

	 * 给老师发评论消息

	 */

	public function fasongxiaoxi($uid){

		$arr = array(

			'sid'     => 0,

			'rid'     => $uid,

			'content' => "您收到了新的的评价，您可以在课程安排中查看并进行回复。",

			'type'    => 4,

			'time'    => time(),

			);

		$this ->add($arr);

	}

	//添加退订中信息

	public function daituidin($uid,$cid){

		$data = D('Course') ->where(array('id' =>$cid)) ->find();

		$nickname = getUserMemberName($uid);

		$arr = array(

			'sid'     => 0,

			'rid'     => $data['uid'],

			'content' => "您的学生".$nickname."进行了退订，退订会在48小时后生效，如您需要申诉请及时联系客服微信hhxxttxs_001。退订生效后系统会将未确认课程部分的款项退回学生，谢谢您的支持。",

			'type'    => 4,

			'time'    => time(),

			);

		$this ->add($arr);

	}

}

